<template>
  <div class="container">
    <div class="table-header">
      <el-input clearable v-model.trim="accountName" :prefix-icon="Search" placeholder="用户名搜索" class="input-with-select"
                style="width: 250px;margin-right: 50px;"/>
      <el-input clearable v-model.trim="account" :prefix-icon="Search" placeholder="账号搜索" class="input-with-select"
                style="width: 250px;margin-right: 50px;"/>
      <el-select v-model="searchRoleId" placeholder="角色搜索" class="input-with-select" clearable filterable
                 @visible-change="visibleChange"
                 style="width: 250px;margin-right: 50px;">
        <el-option label="全部" value=""/>
        <el-option clearable v-for="item in roleData" :key="item.id" :value-key="item.id" :label="item.roleName"
                   :value="item.id"/>
      </el-select>
      <el-button type="primary" :icon="Search" @click="onSearch">
        搜索
      </el-button>
    </div>
    <span v-auth="{tag: '2'}" class="table-button">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">
        新增
      </el-button>
    </span>
    <el-dialog :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               v-model="dialogFormVisible"
               :title="dialogTitle"
               width="700">
      <el-form status-icon :model="form" ref="formRef" label-width="auto" :rules="rules" style="max-width: 400px">
        <el-form-item label="用户名" prop="accountName">
          <el-input clearable placeholder="请输入用户名" v-model="form.accountName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input clearable placeholder="请输入账号" v-model="form.account" autocomplete="off"/>
        </el-form-item>
        <el-form-item v-if="dialogTitle === '新增'" label="密码" prop="password">
          <el-input clearable show-password placeholder="请输入密码" type="password" v-model="form.password"
                    autocomplete="off"/>
        </el-form-item>
        <el-form-item v-if="dialogTitle === '新增'" label="确认密码" prop="confirmPassword">
          <el-input clearable show-password placeholder="请确认密码" type="password" v-model="form.confirmPassword"
                    autocomplete="off"/>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select
              v-model="form.roleIds"
              placeholder="请选择角色"
              @visible-change="visibleChange"
          >
            <el-option
                v-for="item in roleData"
                :value-key="item.id"
                :label="item.roleName"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel(formRef)">取消</el-button>
          <el-button type="primary" @click="dialogConfirm(formRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <div class="table-body">
      <el-table stripe :data="tableData" style="width: 100%" :row-style="{ height: '50px' }">
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
        <el-table-column prop="accountName" label="用户名" width="auto"/>
        <el-table-column prop="account" label="账号" width="auto"/>
        <el-table-column prop="roleName" label="角色" width="auto"/>
        <el-table-column label="账号状态" width="auto">
          <template #default="scope">
            <el-switch
                v-model="scope.row.accountEnable"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button v-auth="{tag: '4'}" type="success" :icon="Edit" @click="handleEdit(scope.$index, scope.row)"/>
            <el-button v-auth="{tag: '4'}" type="warning" :icon="Refresh" @click="handleResetPassword(scope.$index, scope.row)"/>
            <el-button v-auth="{tag: '8'}" type="danger" :icon="Delete" @click="handleDelete(scope.$index, scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :total="total"
      />
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import md5 from 'js-md5';
import {ElMessage, ElMessageBox} from 'element-plus';
import AccountRequest from '@/api/sys/AccountApi.js';
import RoleRequest from '@/api/sys/RoleApi.js';
import {CirclePlus, Delete, Edit, Refresh, Search} from '@element-plus/icons-vue';

let editData = () => ({
  id: '',
  accountName: '',
  account: '',
  password: '',
  confirmPassword: '',
  roleIds: ''
});

let accountName = ref('');
let account = ref('');
let searchRoleId = ref('');
let total = ref(0);
let pageSize = ref(10);
let formRef = ref('');
let dialogFormVisible = ref(false);
let dialogTitle = ref('新增');
let currentPage = ref(1);
let form = ref(editData());
let menuId = ref(0);

const tableData = ref([]);
const roleData = ref([]);

onMounted(() => {
  menuId.value = history.state.m;
  getAccountList();
});

const getRoleList = () => {
  RoleRequest.queryRoleList({
    menuId: menuId.value,
    pageNum: 1,
    pageSize: 999
  }).then(res => {
    roleData.value = res.data;
  });
};

const visibleChange = (isShow) => {
  if (isShow && roleData.value.length === 0) {
    getRoleList();
  }
};

const handleStatusChange = (row) => {
  ElMessageBox.confirm(`确定要${row.accountEnable ? '启用' : '禁用'}该账号吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    AccountRequest.changeStatus(row.id, {
      menuId: menuId.value,
      enable: row.accountEnable
    }).then(res => {
      ElMessage({
        type: 'success',
        message: '操作成功',
      });
    }).catch(() => {
      row.accountEnable = !row.accountEnable;
    });
  }).catch(() => {
    row.accountEnable = !row.accountEnable;
    ElMessage({
      type: 'info',
      message: '已取消',
    });
  });
};

const getAccountList = () => {
  AccountRequest.queryAccountList({
    menuId: menuId.value,
    accountName: accountName.value,
    account: account.value,
    roleId: searchRoleId.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }).then(res => {
    total.value = res.total;
    tableData.value = res.data;
  });
};

const onSearch = () => {
  currentPage.value = 1;
  getAccountList();
};

const dialogCancel = (formRef) => {
  dialogFormVisible.value = false;
  formRef.resetFields();
};

const dialogConfirm = (formRef) => {
  formRef.validate(val => {
    if (val) {
      AccountRequest.addAccount({
        ...form.value,
        menuId: menuId.value,
        password: md5.md5(form.value.password ? form.value.password : '123456'),
        roleIds: form.value.roleIds,
      }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        });
        getAccountList();
        formRef.resetFields();
        dialogFormVisible.value = false;
      });
    }
  });
};

const handleAdd = () => {
  form.value = editData();
  dialogTitle.value = '新增';
  dialogFormVisible.value = true;
};

const handleEdit = (index, row) => {
  form.value = {...row};
  dialogTitle.value = '编辑';
  dialogFormVisible.value = true;
};

const handleResetPassword = (index, row) => {
  ElMessageBox.confirm(
      '此账号会重置为默认密码，确认继续吗？',
      '重置密码',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
    AccountRequest.resetPassword(row.id, menuId.value).then(res => {
      ElMessage({
        type: 'success',
        message: '重置成功',
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消',
    });
  });
}

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getAccountList();
};

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '操作不能撤回，确认继续吗？',
      '删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
    AccountRequest.delAccount({
      id: row.id,
      menuId: menuId.value
    }).then(() => {
      getAccountList();
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消',
    });
  });
};

const rules = {
  accountName: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  account: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入账号'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入确认密码'));
        } else {
          if (form.value.password !== value) {
            callback(new Error('两次密码不一致'));
          } else {
            callback();
          }
        }
      }, trigger: 'blur'
    }
  ],
  roleIds: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error('请绑定权限'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
}
</script>
